package com.rh.cloumn;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import renhai.util.DataUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 57556 字段默认值
 */
public class InitMetaObjectHandler implements MetaObjectHandler {
    /**
     * 填充字段 添加
     */
    private final static Map<String, Object> INSERT_MAP = new HashMap<>();
    /**
     * 填充字段修改
     */
    private final static Map<String, Object> UPDATE_MAP = new HashMap<>();

    static {
        INSERT_MAP.put("createTime", DataUtil.getDataTime());
        INSERT_MAP.put("updateTime", DataUtil.getDataTime());
        INSERT_MAP.put("status", 0);
    }

    static {
        UPDATE_MAP.put("updateTime", DataUtil.getDataTime());
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        INSERT_MAP.forEach((k, v) -> {
            Object column = getFieldValByName(k, metaObject);
            if (column == null) {
                if (k.contains("Time")) {
                    setFieldValByName(k, new Date(), metaObject);
                } else {
                    setFieldValByName(k, v, metaObject);
                }

            }
        });
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        System.out.println(UPDATE_MAP);
        UPDATE_MAP.forEach((k, v) -> {
            Object column = getFieldValByName(k, metaObject);
            if (column == null) {
                if (k.contains("Time")) {
                    setFieldValByName(k, new Date(), metaObject);
                } else {
                    setFieldValByName(k, v, metaObject);
                }
            }
        });
    }
}
